package cn.catsdad.service.impl;

import cn.catsdad.base.service.impl.BaseServiceImpl;
import cn.catsdad.dto.DepartmentUserDTO;
import cn.catsdad.repository.DepartmentUserRepository;
import cn.catsdad.service.api.DepartmentUserService;
import cn.catsdad.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 部门用户关联数据service实现
 *
 * @author xuyonglong
 * @version V1.0 2023/4/12
 */
@Service
public class DepartmentUserServiceImpl extends BaseServiceImpl<DepartmentUserDTO, Long, DepartmentUserRepository>
        implements DepartmentUserService {

    /**
     * 根据用户id查询部门id
     *
     * @param userId 用户id
     * @return 部门id
     */
    public Long queryDepartmentIdByUserId(Long userId) {
        Long result = null;
        if (userId != null) {
            List<DepartmentUserDTO> departmentUsers = repository.findByUserIdIn(Collections.singleton(userId));
            if (StringUtil.isNotEmpty(departmentUsers)) {
                result = departmentUsers.stream()
                        .map(DepartmentUserDTO::getDepartmentId)
                        .filter(Objects::nonNull)
                        .findFirst().orElse(null);
            }
        }
        return result;
    }

    @Override
    public List<DepartmentUserDTO> queryByUserIdIn(Collection<Long> userIds) {
        List<DepartmentUserDTO> result = new ArrayList<>();
        if (StringUtil.isNotEmpty(userIds)) {
            result = repository.findByUserIdIn(userIds);
        }
        return result;
    }

    @Transactional
    public void deleteByUserIdIn(Collection<Long> userIds) {
        if (userIds != null) {
            repository.deleteByUserIdIn(userIds);
        }
    }

}
